import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/constants.dart';
import 'package:seedfour/app/models/notice_v2_entity.dart';
import 'package:seedfour/app/remote/request.dart';
import 'package:seedfour/app/views/module_notice/notice_detail/state.dart';
import 'package:seedfour/app/views/module_notice/notice_report/logic.dart';

import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class NoticeDetailLogic extends GetxController {
  final NoticeDetailState state = NoticeDetailState();

  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  static const String actionReceive = 'receive';

  late int id;

  @override
  void onInit() {
    super.onInit();
    id = Get.arguments;

    state.ownerUid.value = commonService.getUser().uid ?? '';
    _reload();
  }

  // 成交案源
  void dealNotice() async {
    dynamic result =
        await Get.toNamed(RouteGet.noticeSelectCase, arguments: id);
    if (result != null && result == true) {
      _reload();
    }
  }

  // 领取案源
  void receiveNotice() => request(() async {
        var res = await apiService.noticeAction(actionReceive, id: id);
        if (res != null) {
          EasyLoading.showInfo('领取成功');
          _reload();
        } else {
          EasyLoading.showError('领取失败，请稍后重试!');
        }
      }, showLoading: true, message: '正在领取案源');

  // 案源进展
  void toReportProgress() async {
    dynamic result = await Get.toNamed(RouteGet.noticeReport,
        arguments: NoticeReportParams(
            noticeId: state.noticeData.value.id,
            reportAction: NoticeReportLogic.actionProgress));

    if (result != null && result == true) {
      _reload();
    }
  }

  // 退回案源
  void toReportReturn() async {
    dynamic result = await Get.toNamed(RouteGet.noticeReport,
        arguments: NoticeReportParams(
            noticeId: state.noticeData.value.id,
            reportAction: NoticeReportLogic.actionReturn));

    if (result != null && result == true) {
      _reload();
    }
  }

  // 查看案件详情
  void toCaseDetail(String caseId) {
    Get.toNamed(RouteGet.caseDetail, arguments: caseId);
  }

  void _reload() {
    state.isLoading.value = true;
    state.noticeInfoList.clear();
    state.noticeReceiverList.clear();
    _getNoticeDetail(id);
  }

  void _getNoticeDetail(int id) async {
    state.isLoading.value = true;
    var res = await apiService.getNoticeDetail(id, commonService.getRole());
    if (res != null) {
      state.noticeData.value = res;

      _setNoticeInfoList(state.noticeData.value);
      _setReceiveInfoList(state.noticeData.value);
    }
    state.isLoading.value = false;
  }

  // 设置案源信息栏目数据
  void _setNoticeInfoList(NoticeV2Entity entity) {
    state.noticeInfoList.add(
        NoticeDetailSubItemInfo(title: '案源描述', content: entity.content ?? ''));
    if (entity.subjectAmount != null) {
      state.noticeInfoList.add(NoticeDetailSubItemInfo(
          title: '标的额', content: entity.subjectAmount ?? ''));
    }
    if (entity.servicePrice != null) {
      state.noticeInfoList.add(NoticeDetailSubItemInfo(
          title: '服务价格', content: entity.servicePrice ?? ''));
    }
    if (entity.cooperRatio != null) {
      state.noticeInfoList.add(NoticeDetailSubItemInfo(
          title: '案源合作比例',
          content: entity.cooperRatio != null && entity.cooperRatio! > 0
              ? '${entity.cooperRatio}%'
              : ''));
    }
    var contact = '';

    if (entity.receiveUid == state.ownerUid.value) {
      contact += '${entity.phoneNumber}(当事人)';
      if (entity.ownerContact == 1) {
        contact += '\n${entity.ownerMobile}(发布者)';
      }
    } else {
      contact = '领取后可以获得联系方式';
    }

    state.noticeInfoList
        .add(NoticeDetailSubItemInfo(title: '联系方式', content: contact));
  }

  // 设置案源领取栏目数据
  void _setReceiveInfoList(NoticeV2Entity entity) {
    state.noticeReceiverList.add(NoticeDetailSubItemInfo(
        title: '当前状态',
        content: noticeStatus[entity.status]!.$1,
        contentColor: noticeStatus[entity.status]!.$2));

    if (entity.status == 0) {
      state.noticeReceiverList.add(NoticeDetailSubItemInfo(
          title: '你的可用领取配额', content: (entity.quota ?? 0).toString()));
    } else if (entity.status == 1) {
      state.noticeReceiverList.add(NoticeDetailSubItemInfo(
          title: '领取人', content: entity.receiveName ?? ''));
      state.noticeReceiverList.add(NoticeDetailSubItemInfo(
        title: '领取时间',
        content: DateFormat('yyyy-MM-dd HH:mm')
            .format(DateTime.fromMillisecondsSinceEpoch(entity.createdAt!)),
      ));
    } else if (entity.status == 2) {
      state.noticeReceiverList.add(NoticeDetailSubItemInfo(
          title: '领取人', content: entity.receiveName ?? ''));
      state.noticeReceiverList.add(NoticeDetailSubItemInfo(
        title: '领取时间',
        content: DateFormat('yyyy-MM-dd HH:mm')
            .format(DateTime.fromMillisecondsSinceEpoch(entity.createdAt!)),
      ));
      state.noticeReceiverList.add(NoticeDetailSubItemInfo(
          title: '关联案件', content: entity.caseName ?? ''));

      var history = entity.history?.firstWhere((element) => element.type == 3);
      // 成交时间
      var dealTime = history == null || history.createdAt == null
          ? ''
          : DateFormat('yyyy-MM-dd HH:mm')
              .format(DateTime.fromMillisecondsSinceEpoch(history.createdAt!));

      state.noticeReceiverList
          .add(NoticeDetailSubItemInfo(title: '成交时间', content: dealTime));
    }
  }
}
